<?php

// +----------------------------------------------------------------------
// | POS机回调
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\notify;

use app\common\controller\Base;
use app\event\app\ExchangeCoupon;
use app\event\ucenter\User as UserEvent;
use app\model\ucenter\User as UserModel;
use app\model\app\GameOrder as GameOrderModel;
use app\model\app\ExchangeCoupon as ExchangeCouponModel;
use app\model\app\ExchangeCouponOrder as ExchangeCouponOrderModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\helper\Str;
use yicmf\tools\HttpService;
use yicmf\tools\Rsa;

class Yqd extends Base
{

    //http://www.yiqida.cn/#/login
    //13461681612  密码 qifan1234 交易密码qifan1234 ee2e43135b5bfed5128d358df619efad

    protected $key = 'ee2e43135b5bfed5128d358df619efad';
    protected $userName = 'qifan123';

    protected $test_pri_key = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALZTEriMSN454ITeo/MDAvJiAKD6RiqXu4eq2yHnHzBpNf+QkpTcIUqwxHspKkUZGF9aOojzUsezrSMV/YdfQEb/xRsLZO85ZLyUo8lKcM+qfmzyx2+B3SMLUkfWrbuao8WVjwyxEheUR7rVmY4gJWcCYwemNDgpCri2iuOlEMZTAgMBAAECgYAZVXpgyaAHvj5emAUV65GJlmkvSmIHjGUoA8Cbzwk8E9Jx/BJcvChQFYx87zUKvDhGajt/SLge5u4kKuu7LKwPNPEeCik1mNdcbrHl9YGDnYK86+46HN8UAExG5g4rfCQBxDl8IgVKK8aTfZikboxoBTq8tI8BR8DZH/QrYlFQmQJBAPYpjbn1hUU4n20JnAc4y+1l8woHSk00sJg/VLWu6VaJf2VxnFZWvRqkSyjfGTAZvFvPBPxGr7aJCNkkNeigNUcCQQC9nGfAkyuP0msnx8Z7ZINSKkvvpxPKw1EPbUTewGMx6NYsM0gOJsPgLjNQEQOG/C3yBQh3ILFKuVy0cUutEhyVAkEAv6pTI7u7bM5Ns8SLrEPY5JtAxUov3DVuWtzUxDHQlQSyIPZ41/DphNjvfH9ZSU6Ajqt+Ij+XiPTh4tCC+QHk+QJAbquXs0MzLeL3QGTOaL8mFxMw91RhrPuLmKGCjTFltH/eYjYcXIYr1fGhaZ5EnMkcWCKv6jhewuqmPXvTW9UycQJAHE3qxreOqLLrvVBoOkkxNYzsVHBUOO1/oPA3yDiwxhlKEGgzOZFf5j24vCF+GrFPg7ssPfj+VO8HraopDMbhjw==';
    protected $test_pub_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2UxK4jEjeOeCE3qPzAwLyYgCg+kYql7uHqtsh5x8waTX/kJKU3CFKsMR7KSpFGRhfWjqI81LHs60jFf2HX0BG/8UbC2TvOWS8lKPJSnDPqn5s8sdvgd0jC1JH1q27mqPFlY8MsRIXlEe61ZmOICVnAmMHpjQ4KQq4torjpRDGUwIDAQAB';


    public function test()
    {

//
//        $arr = ExchangeCouponModel::where('catalog_id', '<>', null)->where('catalog_name', '<>', null)->column('catalog_name', 'catalog_id');
//
//        dump($arr);
//        exit();
        $headers = [];
        //亿奇达查询商品分组列表查询

        //http://open.yiqida.cn/api/UserCommdity/GetCatalogList?timestamp=当前时间戳13位&userName=登录账号&sign

//        $param = [];
//        $param['timestamp'] = time();
//        $param['userName'] = 'qifan123';
//        $param['sign'] = md5($param['timestamp'].$this->key);
//
//        //http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo?timestamp=当前时间戳13位&userName=登录账号&sign=签名
////        $re = HttpService::request('https://dt.htmax.cn/wapi/process/list_app', [],'GET', $headers);
////        dump($re['content']);
////        $re = HttpService::request('https://dt.htmax.cn/wapi/process/list_apprw', ['appid'=>798],'GET', $headers);
////        $re = HttpService::request('http://open.yiqida.cn/api/UserCommdity/GetCatalogList?timestamp=当前时间戳13位&userName=登录账号&sign', $param,'POST', $headers);
//        $re = HttpService::request('http://open.yiqida.cn/api/UserCommdity/GetCatalogList?timestamp='.$param['timestamp'].'&userName='.$param['userName'].'&sign='.$param['sign'], [],'POST', $headers);
//
//        dump($re);exit();


        $insert = [];


        $param = [];
        $param['timestamp'] = time();
        $param['userName'] = 'qifan123';
        $data['page'] = 1;
        $data['size'] = 600;
//        $data['catalogId'] = 0;
//        $data['name'] = '爱奇艺';
        $param['data'] = json_encode($data);
        $param['sign'] = md5($param['timestamp'] . $param['data'] . $this->key);
        //http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo?timestamp=当前时间戳13位&userName=登录账号&sign=签名
//        $re = HttpService::request('https://dt.htmax.cn/wapi/process/list_app', [],'GET', $headers);
//        dump($re['content']);
//        $re = HttpService::request('https://dt.htmax.cn/wapi/process/list_apprw', ['appid'=>798],'GET', $headers);
        $re = HttpService::request('http://open.yiqida.cn/api/UserCommdity/GetCommodityList?timestamp=' . $param['timestamp'] . '&userName='
            . $param['userName'] . '&sign=' . $param['sign'], json_encode($data), 'POST', $headers);
//        dump($re['content']);
        $data = $re['content']['data'];


        $insertAll = [];
        foreach ($data as $datum) {
            $insert = [];
            foreach ($datum as $index => $item) {
                $insert[Str::snake($index)] = trim($item) ? trim($item) : null;
            }
            $list = ExchangeCouponModel::where('branch_id', $insert['branch_id'])->find();
            if ($list)
            {
                if ($insert['price'] != $list['price'] || $list['status'] != $insert['status'])
                {
                    $list['discount'] = $insert['discount'];
                    $list['is_pre_sale'] = $insert['is_pre_sale'];
                    $list['branch_img'] = $insert['branch_img'];
                    $list['status'] = $insert['status'];
                    $list['name'] = $insert['name'];
                    $list['price'] = $insert['price'];
                    if (isset($insert['advance_price']))
                    {
                        $list['advance_price'] = $insert['advance_price'];
                    }
                    $list['price'] = $insert['price'];
                    if ($list['price'] > $list['show_price']) {
                        $list['is_sale'] = 0;
                        $list['sale_price'] = $list['price'] + ($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'));
                        $list['back_price'] = (($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'))) * (1 - floatval(config('coupon.my_amount')));
                    } else {
                        $list['sale_price'] = $list['price'] + ($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'));
                        $list['back_price'] = (($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'))) * (1 - floatval(config('coupon.my_amount')));

                    }
                    $list->save();
                }

            }else{
                $insert['is_sale'] = 0;
                ExchangeCouponModel::create($insert);
            }
//            if (!ExchangeCouponModel::where('branch_id', $insert['branch_id'])->find()) {
//                ExchangeCouponModel::create($insert);
//            }
        }


        exit();

        exit();
//        $param = [];
//        $param['timestamp'] = time();
//        $param['userName'] = 'qifan123';
//        $param['sign'] = md5($param['timestamp'].$this->key);
//        //http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo?timestamp=当前时间戳13位&userName=登录账号&sign=签名
////        $re = HttpService::request('https://dt.htmax.cn/wapi/process/list_app', [],'GET', $headers);
////        dump($re['content']);
////        $re = HttpService::request('https://dt.htmax.cn/wapi/process/list_apprw', ['appid'=>798],'GET', $headers);
//        $re = HttpService::request('http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo?'.$param['timestamp'].'&userName='.$param['userName'].'&sign='.$param['sign'], [],'GET', $headers);
//        dump($re['content']);
    }


    public function info()
    {


        $index = new ExchangeCoupon();

        dump($index->balance());
        return;
        //http://open.yiqida.cn/api/UserCommdity/GetCatalogList?timestamp=当前时间戳13位&userName=登录账号&sign

        $param = [];
        $param['timestamp'] = time();
        $param['userName'] = $this->userName;
        $data['id'] = 30553;
        $param['data'] = json_encode($data);
        $param['sign'] = md5($param['timestamp'] . $param['data'] . $this->key);

        $re = HttpService::request('http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo?timestamp=' . $param['timestamp'] . '&userName='
            . $param['userName'] . '&sign=' . $param['sign'], json_encode($data), 'POST');
//        dump($re['content']);
        $data = $re['content']['data'];
        dump($data);

    }

    public function order()
    {

        $rsa = new Rsa($this->test_pri_key, $this->test_pub_key);

        //http://open.yiqida.cn/api/UserOrder/CreateOrder?timestamp=当前时间戳13位&userName=登录账号&sign=签名

        $param = [];
        $param['timestamp'] = time();
        $param['userName'] = $this->userName;
        // 爱奇艺周卡
        $data['commodityId'] = 10000608;//商品编号
        $data['external_orderno'] = 1221101;//订单号
        $data['buyCount'] = 1;
        $re = md5($data['external_orderno'] . $this->key);
        $data['remark'] = $rsa->privateEncrypt($data['external_orderno']);
        $data['callbackUrl'] = (string)url('/api/notify/yqd/call', ['rsa' => $re], false, true);
        $data['externalSellPrice'] = 0;//商户平台卖价，小数类型，默认请传0，建议传入，防止商品价格变更造成溢价亏损
        $data['template'] = [urlencode('215033733')];
        $param['data'] = json_encode($data);
        $param['sign'] = md5($param['timestamp'] . $param['data'] . $this->key);

        $re = HttpService::request('http://open.yiqida.cn/api/UserOrder/CreateOrder?timestamp=' . $param['timestamp'] . '&userName='
            . $param['userName'] . '&sign=' . $param['sign'], json_encode($data), 'POST');
//        dump($re['content']);
        dump($re);
        if ($re['content']['code'] == 200) {
            $res = $re['content']['data'];
            $insert = [];
            $insert['sn'] = $data['external_orderno'];
            foreach ($res as $index => $item) {
                $insert[Str::snake($index)] = trim($item) ? trim($item) : null;
                if ($index == 'template') {
                    $insert[Str::snake($index)] = json_decode($item, true);
                }
            }
            $insert['status'] = 0;
            $order = ExchangeCouponOrderModel::create($insert);

            dump($order);
        }

//        "orderNo":"B120210923164437556288161",//亿奇达订单号
//            "orderId":124900067,//亿奇达订单Id
//            "virtualDelivery":3,// 3.官方直充  6卡密
//            "branchId":30366,//品牌Id
//            "name":"全国三网通话费50元",//产品名称
//            "actualPrice":46.250,//订单金额
//            "preSaleDesc":""//预售说明
//        array(7) {
//        ["orderNo"] => string(25) "B520241128141158219794390"
//        ["orderId"] => int(426249153)
//        ["virtualDelivery"] => int(3)
//        ["branchId"] => int(32058)
//        ["name"] => string(6) "测试"
//        ["actualPrice"] => float(0.1)
//        ["preSaleDesc"] => string(0) ""
//}
    }

    public function good()
    {

        $param = $this->request->param();
        foreach ($param as $index => $item) {
            $insert[Str::snake($index)] = trim($item) ? trim($item) : null;
            if ($index == 'template') {
                $insert[Str::snake($index)] = json_decode($item, true);
            }
        }

        $list = ExchangeCouponModel::where('main_id', $insert['main_id'])->find();
        if ($list) {
//            ExchangeCouponModel::where('main_id', $insert['main_id'])->allowField(['discount', 'is_pre_sale', 'branch_img', 'status', 'name', 'advance_price'])->update($insert);

            $list['discount'] = $insert['discount'];
            $list['is_pre_sale'] = $insert['is_pre_sale'];
            $list['branch_img'] = $insert['branch_img'];
            $list['status'] = $insert['status'];
            $list['name'] = $insert['name'];
            $list['price'] = $insert['price'];
            if (isset($insert['advance_price']))
            {
                $list['advance_price'] = $insert['advance_price'];
            }
            $list['price'] = $insert['price'];
            if ($list['price'] > $list['show_price']) {
                $list['is_sale'] = 0;
                $list['sale_price'] = $list['price'] + ($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'));
                $list['back_price'] = (($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'))) * (1 - floatval(config('coupon.my_amount')));
            } else {
                $list['sale_price'] = $list['price'] + ($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'));
                $list['back_price'] = (($list['show_price'] - $list['price']) * floatval(config('coupon.add_price'))) * (1 - floatval(config('coupon.my_amount')));

            }
            $list->save();
        }
    }

    public function call()
    {
        $param = $this->request->param();
        //        $test = [
//            'sign' => '4a52f91c15e28dfcf027ab427190c515',
//            'orderNo' => 'B520241128141508392996776',
//            'Id' => 426249987,
//            'status' => 5,
//            'msg' => '重复推送',
//            'mobile' => '',
//            'shopId' => 0,
//            'name' => '测试',
//            'actualPrice' => 0.0,
//            'payPrice' => 0.1,
//            'format' => '',
//            'branchId' => 10000221,
//            'externalOrderno' => '1732774508',
//            'img' => 'http://api.shangmeng.top/upload/2022/7f/1b/7f2846ee1b071b80032be20307563cc1.jpg',
//            'kami' => NULL,
//            'uuId' => '99a919f3-ca57-453e-808b-3b38c7de4882',
//        ];


        Log::write($this->request->server());
        Log::write($this->request->param());

        if (isset($param['rsa']) && $param['rsa'] == md5($param['externalOrderno'] . $this->key)) {
            $param = $this->request->param();
            $param['order_id'] = $param['Id'];
            unset($param['shopId']);
            unset($param['Id']);
            unset($param['uuId']);
            unset($param['controller']);
            unset($param['action']);
            foreach ($param as $index => $item) {
                $insert[Str::snake($index)] = $item;
            }
            $event = new ExchangeCoupon();
            $re = $event->endPay($insert);
            Log::write($insert);
            if ($re['code'] == 0) {
                return 'ok';
            } else {
                return 'fail';
            }
        } else {
            return 'fail';
        }

    }


}
